# -*- coding: utf-8 -*-

#
# fusion.http.Person
#
# Copyright 2008 Helsinki Institute for Information Technology
# and the authors.
#
# Authors: Harri Hämäläinen <hhamalai@iki.fi>
#

# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

from fusion.db.exceptions import Unauthorized
from fusion.db.profile import Profile
from fusion.http.FusionApp import FusionApp, Response, invitations
from fusion.http.Domain import Domain
from fusion.http.util import escape_html, make_clickable_urls
from string import Template
import logging, simplejson
import re


T_profile = Template('''
    ${header}

    <h2>${name}</h2>

    <div class="picture">
    ${profile_pic}
    </div>

    ${pending_invitation}
    
    ${header_personal}
    <p>
    ${born} 
    ${gender}
    ${_personal}
    </p>
   
    <p>
    ${country}
    ${region}
    ${city}
    ${_location}
    </p>
    
    <p>
    ${website}
    ${phone}
    ${email}
    ${im}
    ${_contact}
    </p>
    
    <p>
    ${custom_sections}
    </p>
    ${header_about}
    <p class="about">
    ${about}
    </p>
    
    <div>
    <div style="float:left;position:top;">${friendlist}</div>
    <div style="float:left;position:top;">${grouplist}</div>
    <div style="float:left;position:top;padding-left:10%;">${datasets}</div>
    </div>
    ${buttons}
    ''')



class Person(Domain):
    def do_GET(self):
        if self.environ.get('HTTP_HOST') == 'my.hexlabel.net':
            response = Response(status=301)
            url = 'http://%s.hexlabel.net/person%s' % (self.db.get_my_iid(),
                  self.request_url(host=False))
            if '?' not in url:
                url += '?'
            response.add_header('Location', url)
            return response
        
        patterns = {'/': self.redirect_to,
                    '/person': self.output_profile,
                    '/list_friends': self.output_full_friendlist,
                    '/remove_friend': self.output_remove_friend,
                    '/content': self.get
        }
        
        return self.match_response(patterns)
    

    def do_POST(self):
        def process_fields(field_names, form, public=False):
            for x in field_names:
                try:
                    section, _, field = x.split('#')
                    value = form.getvalue(x)
                    if value:
                        profile.add_field(section, field, form.getvalue(x), public=public)
                except ValueError:
                    logging.warn("Unable to extract posted values")
                    
        form = self.read_request_form()
        response = Response()
        
        if form.getvalue("change_profile_data"):
            profile = Profile()
            profile.read(self.db, self.db.get_my_iid())
            profile.clear_all_fields()
            
            name = (form.getvalue('name') or '').strip()
            if name:
                profile.name = name

            if form.getvalue('remove_pic'):
                profile.pic = None            
            profile_picture = form.getvalue('profile_picture')
            if profile_picture:
                profile.pic = profile_picture
             
            form_keys = set(form.keys()) - set(['name', 'about', 'remove_pic', 
                                                'profile_picture',
                                                'change_profile_data'])
            public_selectors = set([x for x in form_keys if x.startswith('_public_')])
            form_keys = form_keys - public_selectors
            public_fields = set([x for x in form_keys if '_public_'+x in public_selectors])
            restricted_fields = form_keys - public_fields 
            
            process_fields(public_fields, form, public=True)
            process_fields(restricted_fields, form)
            
            if '_public_about' in public_selectors:
                profile.set_about(form.getvalue('about') or '', public=True)
            else:
                profile.set_about(form.getvalue('about') or '')
            
            try:
                profile.write(self.db, self.iid)
            except (Unauthorized, LookupError):
                pass
            response = self.do_GET()
            
        elif form.getvalue('remove_friend'):
            iid = form.getvalue("iid")
            if iid:
                self.db.revoke_friendship(iid)
            response = Response(301)
            response.add_header('Location', '/list_friends')
    
        elif form.getvalue('accept_invitation'):
            iid = form.getvalue('iid')
            self.accept_invitation(iid)
            response = self.do_GET()

        elif form.getvalue('decline_invitation'):
            iid = form.getvalue('iid')
            self.decline_invitation(iid)
            response = self.do_GET()
        
        elif form.getvalue('get_invitation'):
            result = self.invitation(form)
            if result:
                response = result
            else:
                response = self.do_GET()

        if response:
            return response
        else:
            self.post()

            
    def redirect_to(self):
        response = Response(status=301)
        response.add_header('Location', '/person')
        return response

        
    def output_profile_grouplist(self):
        def output_group_link(iid):
            name = self.db.get(iid,'info/name.txt')
            return '<li><a href="http://%s.hexlabel.net">%s</a></li>' % (iid,
                     name or iid)

        T_grouplist = Template('''<h3>
                                <!--<a href="/list_groups">-->Groups<!--</a>-->
                                </h3>
                                <ul>${groups}
                                ${groups_unverified}</ul>''')
        
        group_iids, unverified = self.db.report_memberships(self.iid)
        
        if len(group_iids) == 0 and unverified == 0:
            return ''
        
        groups = ''.join([output_group_link(iid) for iid in group_iids])
        
        profile_values = {
            'groups': groups
        }
        
        if unverified > 0:
            profile_values['groups_unverified'] = '<li><em>%s unverified</em></li>' % unverified
        else:
            profile_values['groups_unverified'] = ''
        
        return T_grouplist.substitute(profile_values)
    
    def output_profile_grouplist(self):
        def output_group_link(iid):
            name = self.db.get(iid, 'info/name.txt')
            return '<li><a href="http://%s.hexlabel.net">%s</a></li>' % (iid,
                    escape_html(name) or iid)

        
        return '''<h3>Groups</h3>
               <ul>
                %s
               </ul>''' % ''.join(output_group_link(x) for x in self.db.list_memberships(self.iid))
       

    def output_profile_friendlist(self):
        def output_friend_link(iid):
            profile = Profile()
            profile.read(self.db, iid)
            return '<li><a href="http://%s.hexlabel.net">%s</a></li>' % (iid,
                     escape_html(profile.name) or iid)

        T_friendlist = Template('''<h3>
                                <a href="/list_friends">Friends</a>
                                </h3>
                                <ul>${friends}
                                ${friends_unverified}</ul>''')
        
        friend_iids, unverified = self.db.report_friends(self.iid)
        
        if len(friend_iids) == 0 and unverified == 0:
            return ''
        
        friends = ''.join([output_friend_link(iid) for iid in friend_iids])
        
        profile_values = {
            'friends': friends
        }
        
        if unverified > 0:
            profile_values['friends_unverified'] = '<li><em>%s unverified</em></li>' % unverified
        else:
            profile_values['friends_unverified'] = ''
        
        return T_friendlist.substitute(profile_values)

    def output_full_friendlist(self):
        def available_options(db, collection_iid, friend_iid):
            options = ''
            if db.get_my_iid() == collection_iid:
                options += '<a href="/remove_friend?friend_iid=%s">Remove from friends</a>' % friend_iid
            return options
        
        friend_iids, unverified = self.db.report_friends(self.iid)
        profile = Profile()
        profile.read(self.db, self.iid)
        output = '<h3>Friends of %s</h3><table>' % profile.name
    
        
        for iid in friend_iids:
            profile.read(self.db, iid)
            
            pic_path = 'http://%s.hexlabel.net/content%s' % (iid, profile.pic_path)
            if not profile.pic:
                pic_path = 'http://%s.hexlabel.net/static/dummy.png' % iid
            
            location = '%s %s' % (profile.get_field('location', 'country') or '', 
                                  profile.get_field('location', 'city') or '')

            output += '''<tr><td>
                        <img src="%s" style="max-width: 100px; max-height: 100px" />
                        </td><td>
                        <a href="http://%s.hexlabel.net">%s</a><br />
                        %s
                        </td><td>
                        %s
                        </td>
                        </tr>''' % (pic_path, iid, escape_html(profile.name) or iid, 
                                    escape_html(location), available_options(self.db, self.iid, iid))
        output += '</table>'
        
        response = Response()
        response.add_header('Content-Type', 'text/html;charset=utf-8')
        response.append_output(self.create_page('My friends', output.encode('utf-8')))
        return response

    def output_remove_friend(self):
        
        requested_iid = self.querydict.get('friend_iid')
        if len(requested_iid) > 0:
            requested_iid = requested_iid[0]
        else:
            return ''
        
        target = None
        friend_iids, unverified = self.db.report_friends(self.db.get_my_iid())
        for iid in friend_iids:
            if iid == requested_iid:
                target = iid
        
        if target == None:
            return ''
        
        profile = Profile()
        profile.read(self.db, target)
        
        content = Template('''<table>
            <tr><td><img src="http://${iid}.hexlabel.net/${pic}" /></td>
            <td>Are you sure you want to remove <a href="http://${iid}.hexlabel.net">${name}</a> from your friends?
            <form action="" method="post">
            <input type="hidden" name="iid" value="${iid}" />
            <input type="submit" name="remove_friend" value="Remove" />
            </form></td></tr>
            </table>
            ''')
        content = content.substitute({
             'iid': iid, 
             'pic': profile.pic_path or '/static/dummy.png', 
             'name': profile.name or iid
             })
        
        response = Response()
        response.add_header('Content-Type', 'text/html;charset=utf-8')
        response.append_output(self.create_page('Remove from friends', content))
        return response

    def output_edit_profile(self):
        def textarea(name, text, checked=False):
            selected = ''
            if checked:
                selected = 'checked="checked"'
            return '''<input type="checkbox" name="_public_%s" %s>
                    <textarea rows="8" cols="40" name="%s" />%s</textarea>
                    ''' % (name, selected, name, text or '')

        def show_field(profile, section, field, friendly_name, show_empty=False):
            def check_gender(gender):
                options = {'male_checked': '',
                          'female_checked': '',
                          'unspecified_checked': ''
                }
                if gender.lower() == 'male':
                    options['male_checked'] = 'checked="checked"'
                if gender.lower() == 'female':
                    options['female_checked'] = 'checked="checked"'
                if not options['male_checked'] and not options['female_checked']:
                    options['unspecified_checked'] = 'checked="checked"'
                return options
                
            T_input = Template('''<input type="checkbox" name="_public_${identifier}" ${checked}/> 
                                  %s: <input type="text" name="${identifier}" value="${value}" />
                                  <br />''' % friendly_name)
            
            input_values = {}
            form_fields = []
            
            gender_field = False
            if section == 'personal' and field == 'gender':
                gender_field = True
                T_input = Template('''<input type="checkbox" name="_public_${identifier}" ${checked}/> 
                                  %s: <input type="radio" name="${identifier}" ${male_checked} value="Male" /> Male
                                  <input type="radio" name="${identifier}" ${female_checked} value="Female" /> Female
                                  <input type="radio" name="${identifier}" ${unspecified_checked} value="" /> Unspecified
                                  <br />''' % friendly_name)
                
            
            profile_fields = profile.list_field_values_and_visibility(section, field)
            if len(profile_fields) == 0 and show_empty:
                profile_fields.append(('', ''))
            i = 0
            for value, public in profile_fields:
                input_values.update({'identifier': '%s#%s#%s' % (section, i, field),
                                     'value': escape_html(value),
                                     'checked': 'checked="checked"' if public else ''
                                     })
                if gender_field:
                    input_values.update(check_gender(value))
                form_fields.append(T_input.substitute(input_values))
                i += 1    
            return ''.join(form_fields)
            
        def show_section(profile, show_field, section, exclude=[]):
            tmp = []
            for field in profile.list_field_names(section, exclude=exclude):
                tmp.append(show_field(profile, section, field, field.capitalize()))
            return ''.join(tmp)
        
        profile = Profile()
        profile.read(self.db, self.iid)
        profile_values = {
          'header': '<form method="post" enctype="multipart/form-data" action="/">',
          'buttons': '''<div class="buttons">
              <input type="submit" name="change_profile_data" value="Save Changes" />
              </div></form>''',
          'friendlist': '',
          'grouplist': '',
          'datasets': '',
          'pending_invitation': ''
        }
        
        profile_values['name'] = '<input type="text" name="name" value="%s" />' % profile.name
        
        profile_pic = '/static/dummy.png'
        if profile.pic:
            profile_pic = '/content%s' % profile.pic_path
        profile_values['profile_pic'] = '''<img src="%s" alt="" id="pic"/><br />
                                        <input type="file" name="profile_picture" />
                                        <br />Delete picture
                                        <input type="checkbox" name="remove_pic" />
                                        ''' % profile_pic
        
        profile_values['header_about'] = '<h3>About</h3>'
        if profile.public.about:
            profile_values['about'] =  textarea('about', profile.public.about, True)
        else:
            profile_values['about'] =  textarea('about', profile.restricted.about or '')
        
        header_personal = '''<h3>Personal</h3><br />
                             <img src="/static/arrow.png" alt="&#x2B10;" 
                             style="height: 1em; padding: 0 0.4em;"/>Public?'''
        profile_values['header_personal'] = header_personal
        
        profile_values['born'] = show_field(profile, 'personal',
                                            'born', 'Year of birth', show_empty=True)
        profile_values['gender'] = show_field(profile, 'personal',
                                              'gender', 'Gender', show_empty=True)
        profile_values['_personal'] = show_section(profile, show_field,
                                                   'personal', exclude=['born', 'gender'])
        
        profile_values['country'] = show_field(profile, 'location',
                                               'country', 'Country', show_empty=True)
        profile_values['region'] = show_field(profile, 'location',
                                              'region', 'State/Province', show_empty=True)
        profile_values['city'] = show_field(profile, 'location',
                                            'city', 'City', show_empty=True)
        profile_values['_location'] = show_section(profile, show_field,
                                                   'location', exclude=['country', 'region', 'city'])
        
        profile_values['website'] = show_field(profile, 'contact',
                                               'website', 'Website', show_empty=True)
        profile_values['phone'] = show_field(profile, 'contact',
                                             'phone', 'Phone', show_empty=True)
        profile_values['email'] = show_field(profile, 'contact',
                                             'email', 'Email', show_empty=True)
        profile_values['im'] = show_field(profile, 'contact',
                                          'im', 'Instant Messaging', show_empty=True)
        profile_values['_contact'] = show_section(profile, show_field,
                                                  'contact', exclude=['website', 'phone', 'email', 'im'])
        
        tmp = []
        for section in profile.list_section_names(exclude=['personal', 'location', 'contact']):
            tmp.append('<h3>%s</h3>' % section.capitalize())
            tmp.append(show_section(profile, show_field, section))
        profile_values['custom_sections'] = ''.join(tmp)        
        
        return self.create_page('Profile',
                                T_profile.safe_substitute(profile_values).encode('utf-8'),
                                style='edit')

    def format_field(self, friendly_name, value):
        if value:
            if type(value) != list:
                value = [value]
            return ''.join(['%s: %s <br />\n' % (friendly_name, make_clickable_urls(v))
                            for v in value if type(v) 
                            in [str, unicode]])
        else:
            return ''
            
    def update_fields(self, profile_values, profile, format_field, section, 
                      items=[], multivalued=False, include_customs=True):
        '''
        Adds keys to profile_values from given profile object's section, 
        formated by field_format function. items lists the keys to include.
        If multivalued is set to True,  the field may have multiple values. 
        if include_customs is set to True, all other keys from given section
        not specified in items will be added to key specified by underscore
        section (for example '_personal').
        '''
        for field, friendlyname in items:
            if multivalued:
                tmp = []
                for value in profile.list_field_values(section, field):
                    tmp.append(self.format_field(friendlyname, value))
                profile_values[field] = ''.join(tmp)
            else:    
                profile_values[field] = self.format_field(friendlyname, profile.get_field(section, field))
        if include_customs:
            section_name = '_'+section
            profile_values[section_name] = []
            for field in profile.list_field_names(section, exclude=[x[0] for x in items]):
                for value in profile.list_field_values(section, field):
                    profile_values['_'+section].append(self.format_field(field.capitalize(),
                                                                    value))
            profile_values[section_name] = ''.join(profile_values[section_name])


    def output_view_profile(self):  
        profile = Profile()
        profile.read(self.db, self.iid)
        profile_values = {
          'header': '',
          'friendlist': self.output_profile_friendlist(),
          'grouplist': self.output_profile_grouplist(),
          'datasets': self.domain_datasets(),
          'name': profile.name or self.iid,
          'pending_invitation': self.pending_invitation(self.environ),
          'buttons': ''
        }
    
        if profile.public.about:
            profile_values['about'] = re.sub('\n', '<br />\n',
                                          make_clickable_urls(profile.public.about))
        else:
            profile_values['about'] = re.sub('\n', '<br />\n',
                                          make_clickable_urls(profile.restricted.about))
        profile_values['header_about'] = '<h3>About</h3>' if profile_values['about'] else ''
        
        profile_pic = '/static/dummy.png'
        if profile.pic:
            profile_pic = '/content%s' % profile.pic_path
        profile_values['profile_pic'] = '<img src="%s" alt="" id="pic"/>' % profile_pic
        
        personal = [('born', 'Year of birth'),
                     ('gender', 'Gender')]

        location = [('country', 'Country'),
                  ('region', 'State/Province'),
                  ('city', 'City')]

        contact = [('website', 'Website'),
                  ('phone', 'Phone'),
                  ('email', 'Email'),
                  ('im', 'Instant Messaging')]
        
        self.update_fields(profile_values, profile, self.format_field, 'personal', personal)
        self.update_fields(profile_values, profile, self.format_field, 'location', location)
        self.update_fields(profile_values, profile, self.format_field, 'contact', contact, multivalued=True)
        
        custom_sections = []
        for section in profile.list_section_names(exclude=['personal', 'contact', 'location']):
            custom_sections.append('<h3>%s</h3>' % section.capitalize())
            for name in profile.list_field_names(section):
                for value in profile.list_field_values(section, name):
                    custom_sections.append(self.format_field(name.capitalize(), value))                   
        profile_values['custom_sections']  = ''.join(custom_sections)
        
        profile_values['header_personal'] = ''
        if len(profile.list_section_names()) > 0:
            profile_values['header_personal'] = '<h3>Personal</h3>'
        
        return self.create_page('Profile',
                                T_profile.safe_substitute(profile_values).encode('utf-8'),
                                style='profile')



